package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.order.converter.OrderConverter;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.OrderShipping;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.dto.*;
import com.cskaoyan.order.service.OrderQueryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Qing
 * @since 2022/06/20 15:10
 */
@Slf4j
@Service
public class OrderQueryServiceImpl implements OrderQueryService {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    OrderShippingMapper orderShippingMapper;
    @Autowired
    OrderConverter orderConverter;


    @Override
    public OrderListResponse orderList(OrderListRequest listRequest) {
        OrderListResponse listResponse = new OrderListResponse();

        try {
            listRequest.requestCheck();

            PageHelper.startPage(listRequest.getPage(), listRequest.getSize());
            Example exampleOrder = new Example(Order.class);
            if (listRequest.getSort() != null) {
                exampleOrder.setOrderByClause("create_time" + " " + listRequest.getSort());//todo /n
            }
            exampleOrder.createCriteria().andEqualTo("userId", listRequest.getUserId()).andNotEqualTo("status", -1);//-1 实现逻辑删除
            List<Order> orders = orderMapper.selectByExample(exampleOrder);
            PageInfo<Order> pageInfo = new PageInfo<>(orders);
            long total = pageInfo.getTotal();

            List<OrderDetailInfo> infoList = new ArrayList<>();
            for (Order order : orders) {
                //订单详情
                OrderDetailInfo orderDetailInfo = orderConverter.order2detail(order);

                //订单里面的商品详情
                Example exampleItem = new Example(OrderItem.class);
                exampleItem.createCriteria().andEqualTo("orderId", order.getOrderId());
                List<OrderItem> orderItems = orderItemMapper.selectByExample(exampleItem);
                List<OrderItemDto> orderItemDtos = orderConverter.item2dto(orderItems);

                orderDetailInfo.setOrderItemDto(orderItemDtos);

                //订单的物流信息
                OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(order.getOrderId());
                OrderShippingDto orderShippingDto = orderConverter.shipping2dto(orderShipping);
                orderDetailInfo.setOrderShippingDto(orderShippingDto);

                infoList.add(orderDetailInfo);
            }
            OrderListDto orderListDto = new OrderListDto();
            orderListDto.setData(infoList);
            orderListDto.setTotal(total);
            listResponse.setOrderListDto(orderListDto);
            listResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            listResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());

        } catch (Exception e) {
            log.error("OrderQueryServiceImpl.listOrder Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(listResponse, e);
        }

        return listResponse;
    }

    @Override
    public OrderDetailResponseMy orderDetail(OrderDetailRequest orderDetailRequest) {
        OrderDetailResponseMy orderDetailResponseMy = new OrderDetailResponseMy();
        try {
            //校验参数的合法性
            orderDetailRequest.requestCheck();
//            //进行订单详情查询
            Order order = orderMapper.selectByPrimaryKey(orderDetailRequest.getOrderId());
//            进行订单包含商品的详情查询
            Example example = new Example(OrderItem.class);
            example.createCriteria().andEqualTo("orderId", orderDetailRequest.getOrderId());
            List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
            //进行订单包含shipping的详情查询
            OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(orderDetailRequest.getOrderId());
            // 封装Response中的order信息
            orderDetailResponseMy.setOrderStatus(order.getStatus());
            orderDetailResponseMy.setUserId(Math.toIntExact(order.getUserId()));
            orderDetailResponseMy.setUserName(order.getBuyerNick());
            BigDecimal bigDecimal = new BigDecimal(Double.toString(0));
            List<OrderDetailResponseMy.GoodsListDTO> goodsListDTOS = new ArrayList<>();
            for (OrderItem orderItem : orderItems) {
                bigDecimal = bigDecimal.add(BigDecimal.valueOf(orderItem.getTotalFee()));
                OrderDetailResponseMy.GoodsListDTO goodsListDTO = new OrderDetailResponseMy.GoodsListDTO();
                goodsListDTO.setId(orderItem.getId());
                goodsListDTO.setItemId(String.valueOf(orderItem.getItemId()));
                goodsListDTO.setNum(orderItem.getNum());
                goodsListDTO.setOrderId(orderItem.getOrderId());
                goodsListDTO.setPicPath(orderItem.getPicPath());
                goodsListDTO.setPrice(Integer.valueOf(orderItem.getPrice().intValue()));
                goodsListDTO.setTitle(orderItem.getTitle());
                goodsListDTO.setTotalFee(Integer.valueOf(orderItem.getTotalFee().intValue()));
                goodsListDTOS.add(goodsListDTO);
            }
            orderDetailResponseMy.setGoodsList(goodsListDTOS);
            orderDetailResponseMy.setOrderTotal(bigDecimal);
            orderDetailResponseMy.setStreetName(orderShipping.getReceiverAddress());
            orderDetailResponseMy.setTel(orderShipping.getReceiverPhone());

            orderDetailResponseMy.setCode(SysRetCodeConstants.SUCCESS.getCode());
            orderDetailResponseMy.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        } catch (Exception e) {
            //查询失败and参数校验失败 -> 抛出异常
            log.error("OrderQueryServiceImpl.selectOrderDetail occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(orderDetailResponseMy, e);
        }
        return orderDetailResponseMy;
    }

    @Override
    public OrderListResponse listOrder(OrderListRequest listRequest) {
        OrderListResponse listResponse = new OrderListResponse();

        try {
            listRequest.requestCheck();

            PageHelper.startPage(listRequest.getPage(), listRequest.getSize());
            Example exampleOrder = new Example(Order.class);
            // if (listRequest.getSort() != null) {
            //     exampleOrder.setOrderByClause("create_time");
            // }
            exampleOrder.setOrderByClause("create_time desc");
            exampleOrder.createCriteria().andEqualTo("userId", listRequest.getUserId()).andNotEqualTo("status", -1);//-1 实现逻辑删除
            List<Order> orders = orderMapper.selectByExample(exampleOrder);
            System.out.println("");
            PageHelper.startPage(listRequest.getPage(), listRequest.getSize());
            PageInfo<Order> pageInfo = new PageInfo<>(orders);
            long total = pageInfo.getTotal();

            List<OrderDetailInfo> infoList = new ArrayList<>();
            for (Order order : orders) {
                //订单详情
                OrderDetailInfo orderDetailInfo = orderConverter.order2detail(order);

                //订单里面的商品详情
                Example exampleItem = new Example(OrderItem.class);
                exampleItem.createCriteria().andEqualTo("orderId", order.getOrderId());
                List<OrderItem> orderItems = orderItemMapper.selectByExample(exampleItem);
                List<OrderItemDto> orderItemDtos = orderConverter.item2dto(orderItems);

                orderDetailInfo.setOrderItemDto(orderItemDtos);

                //订单的物流信息
                OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(order.getOrderId());
                OrderShippingDto orderShippingDto = orderConverter.shipping2dto(orderShipping);
                orderDetailInfo.setOrderShippingDto(orderShippingDto);

                infoList.add(orderDetailInfo);
            }
            OrderListDto orderListDto = new OrderListDto();
            orderListDto.setData(infoList);
            // orderListDto.setTotal(total);
            listResponse.setOrderListDto(orderListDto);
            listResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            listResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());

        } catch (Exception e) {
            log.error("OrderQueryServiceImpl.listOrder Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(listResponse, e);
        }

        return listResponse;
    }

    @Override
    public OrderDetailResponseMy selectOrderDetail(OrderDetailRequest orderDetailRequest) {
        OrderDetailResponseMy orderDetailResponseMy = new OrderDetailResponseMy();
        try {
            //校验参数的合法性
            orderDetailRequest.requestCheck();
//            //进行订单详情查询
            Order order = orderMapper.selectByPrimaryKey(orderDetailRequest.getOrderId());
//            进行订单包含商品的详情查询
            Example example = new Example(OrderItem.class);
            example.createCriteria().andEqualTo("orderId", orderDetailRequest.getOrderId());
            List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
            //进行订单包含shipping的详情查询
            OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(orderDetailRequest.getOrderId());
            // 封装Response中的order信息
            orderDetailResponseMy.setOrderStatus(order.getStatus());
            orderDetailResponseMy.setUserId(Math.toIntExact(order.getUserId()));
            orderDetailResponseMy.setUserName(order.getBuyerNick());
            BigDecimal bigDecimal = new BigDecimal(Double.toString(0));
            List<OrderDetailResponseMy.GoodsListDTO> goodsListDTOS = new ArrayList<>();
            for (OrderItem orderItem : orderItems) {
                bigDecimal = bigDecimal.add(BigDecimal.valueOf(orderItem.getTotalFee()));
                OrderDetailResponseMy.GoodsListDTO goodsListDTO = new OrderDetailResponseMy.GoodsListDTO();
                goodsListDTO.setId(orderItem.getId());
                goodsListDTO.setItemId(String.valueOf(orderItem.getItemId()));
                goodsListDTO.setNum(orderItem.getNum());
                goodsListDTO.setOrderId(orderItem.getOrderId());
                goodsListDTO.setPicPath(orderItem.getPicPath());
                goodsListDTO.setPrice(Integer.valueOf(orderItem.getPrice().intValue()));
                goodsListDTO.setTitle(orderItem.getTitle());
                goodsListDTO.setTotalFee(Integer.valueOf(orderItem.getTotalFee().intValue()));
                goodsListDTOS.add(goodsListDTO);
            }
            orderDetailResponseMy.setGoodsList(goodsListDTOS);
            orderDetailResponseMy.setOrderTotal(bigDecimal);
            orderDetailResponseMy.setStreetName(orderShipping.getReceiverAddress());
            orderDetailResponseMy.setTel(orderShipping.getReceiverPhone());

            orderDetailResponseMy.setCode(SysRetCodeConstants.SUCCESS.getCode());
            orderDetailResponseMy.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        } catch (Exception e) {
            //查询失败and参数校验失败 -> 抛出异常
            log.error("OrderQueryServiceImpl.selectOrderDetail occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(orderDetailResponseMy, e);
        }
        return orderDetailResponseMy;
    }
}